package com.rxst.msg.utils;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.rxst.msg.enums.ExcelEnum;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel 工具类
 *
 * @author zgs
 */
public class ExcelUtils {

    /**
     * Excel 导入，默认第一个sheet
     *
     * @param file     文件
     * @param clazz    实体类
     * @param listener 监听器
     * @return
     */
    public static ExcelEnum read(MultipartFile file, Class clazz, AnalysisEventListener listener) {
        if (file == null) {
            return ExcelEnum.ERROR_FILE;
        }
        if (listener == null) {
            return ExcelEnum.ERROR_LISTENER;
        }
        Map<Integer, AnalysisEventListener> maps = new HashMap<>();
        maps.put(0, listener);
        return read(file, clazz, maps);
    }

    /**
     * Excel 本地导入，默认第一个sheet
     *
     * @param filePath 文件
     * @param clazz    实体类
     * @param listener 监听器
     * @return
     */
    public static ExcelEnum read(String filePath, Class clazz, AnalysisEventListener listener) {
        Map<Integer, AnalysisEventListener> maps = new HashMap<>();
        maps.put(0, listener);
        return read(filePath, clazz, maps);
    }

    /**
     * Excel 导入，指定sheet位置
     *
     * @param file     文件
     * @param clazz    实体类
     * @param listener 监听器
     * @param sheet    位置
     * @return
     */
    public static ExcelEnum read(MultipartFile file, Class clazz, AnalysisEventListener listener, Integer sheet) {
        if (file == null) {
            return ExcelEnum.ERROR_FILE;
        }

        if (sheet == null) {
            return ExcelEnum.ERROR_SHEET;
        }
        if (listener == null) {
            return ExcelEnum.ERROR_LISTENER;
        }
        Map<Integer, AnalysisEventListener> maps = new HashMap<>();
        maps.put(sheet, listener);
        return read(file, clazz, maps);
    }

    /**
     * Excel 导入，支持多个个sheet同一个监听器
     *
     * @param file     文件
     * @param clazz    实体类
     * @param listener 监听器
     * @param sheets   位置
     * @return
     */
    public static ExcelEnum read(MultipartFile file, Class clazz, AnalysisEventListener listener, Integer[] sheets) {
        if (file == null) {
            return ExcelEnum.ERROR_FILE;
        }
        if (sheets == null) {
            return ExcelEnum.ERROR_SHEETS;
        }
        if (listener == null) {
            return ExcelEnum.ERROR_LISTENER;
        }
        Map<Integer, AnalysisEventListener> maps = new HashMap<>();
        for (int i = 0; i < sheets.length; i++) {
            maps.put(sheets[i], listener);
        }
        return read(file, clazz, maps);
    }

    /**
     * Excel导入，多个sheet多个监听器
     *
     * @param file  文件
     * @param clazz 实体类
     * @param maps  key：sheet位置 value 监听器
     * @return
     */
    public static ExcelEnum read(MultipartFile file, Class clazz, Map<Integer, AnalysisEventListener> maps) {
        if (maps == null || maps.isEmpty()) {
            return ExcelEnum.ERROR_SHEETS;
        }
        ExcelReader excelReader = null;
        List<ReadSheet> readSheets = new ArrayList<>();
        try {
            for (Integer sheetIndex : maps.keySet()) {
                excelReader = EasyExcel.read(file.getInputStream(), clazz, maps.get(sheetIndex)).build();
                ReadSheet readSheet = EasyExcel.readSheet(sheetIndex).build();
                readSheets.add(readSheet);
            }
            excelReader.read(readSheets);
        } catch (Exception e) {
            return ExcelEnum.ERROR_READ;
        } finally {
            if (excelReader != null) {
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
            }
        }
        return ExcelEnum.SUCCESS;
    }

    /**
     * Excel导入，多个sheet多个监听器
     *
     * @param filePath 本地文件
     * @param clazz    实体类
     * @param maps     key：sheet位置 value 监听器
     * @return
     */
    public static ExcelEnum read(String filePath, Class clazz, Map<Integer, AnalysisEventListener> maps) {
        if (maps == null || maps.isEmpty()) {
            return ExcelEnum.ERROR_SHEETS;
        }
        ExcelReader excelReader = null;
        List<ReadSheet> readSheets = new ArrayList<>();
        try {
            String templateFilePath = ResourceUtils.getURL("classpath:").getPath() + "templates" + File.separator + filePath;
            for (Integer sheetIndex : maps.keySet()) {
                excelReader = EasyExcel.read(templateFilePath, clazz, maps.get(sheetIndex)).build();
                ReadSheet readSheet = EasyExcel.readSheet(sheetIndex).build();
                readSheets.add(readSheet);
            }
            excelReader.read(readSheets);
        } catch (Exception e) {
            return ExcelEnum.ERROR_READ;
        } finally {
            if (excelReader != null) {
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
            }
        }
        return ExcelEnum.SUCCESS;
    }

    /**
     * 导出excel 待定
     *
     * @param response
     * @param clazz
     * @param list
     * @param sheetName
     * @param fileName
     * @return
     * @throws IOException
     */
    public static void write(HttpServletResponse response, Class clazz, List list, String sheetName, String fileName) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), clazz).autoCloseStream(Boolean.FALSE).sheet(sheetName)
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSONUtil.toJsonStr(map));
        }
    }

    public static void write(HttpServletResponse response, String fileName, String templateFileName, List data) {
        write(response, fileName, templateFileName, 0, data);
    }

    /**
     * 导出excel 单个sheet
     *
     * @param response
     * @param fileName
     * @param templateFileName
     * @param sheetIndex
     * @param data
     */
    public static void write(HttpServletResponse response, String fileName, String templateFileName, Integer sheetIndex, List data) {
        Map<Integer, List> maps = new HashMap<>();
        maps.put(sheetIndex, data);
        write(response, fileName, templateFileName, maps);
    }

    /**
     * 导出excel，基于模板，忽略数据专职于数据，支持多个sheet
     *
     * @param response
     * @param fileName         文件名
     * @param templateFileName 模板名称
     * @param maps             key：sheet value：data
     */
    public static void write(HttpServletResponse response, String fileName, String templateFileName, Map<Integer, List> maps) {
        ExcelWriter excelWriter = null;
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //response.setContentType("application/octet-stream;charset=UTF-8");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            String templateFilePath = ResourceUtils.getURL("classpath:").getPath() + "templates" + File.separator + templateFileName;
            excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateFilePath).build();
            for (Integer sheetIndex : maps.keySet()) {
                WriteSheet writeSheet = EasyExcel.writerSheet(sheetIndex).build();
                excelWriter.fill(maps.get(sheetIndex), writeSheet);
            }
        } catch (IOException e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            try {
                response.getWriter().println(JSONUtil.toJsonStr(map));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    /**
     * 下载模板
     *
     * @param response
     * @param path
     */
    public static void downloadExcel(HttpServletResponse response, String path) {
        try {
            ClassPathResource classPathResource = new ClassPathResource(path);
            String filename = classPathResource.getFilename();
            InputStream inputStream = classPathResource.getInputStream();
            response.setContentType("application/zip");
            OutputStream out = response.getOutputStream();
            filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename*=utf-8''" + filename);
            int b = 0;
            byte[] buffer = new byte[1048576];

            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) {
                    out.write(buffer, 0, b);
                }
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
        }

    }
}
